package com.one.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.one.bean.Product;

import com.one.constant.RabbitMQConstant;
import com.one.constant.SystemConstant;
import com.one.mapper.ProductMapper;
import com.one.util.RedisUtils;
import com.one.utils.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName: RabbitMQDirectConsumer
 * @Auther: yph
 * @Date: 2022/1/3 14:54
 * @Description: 直连队列消费者
 */
@Slf4j
@Component
public class RabbitMQDirectConsumer {
    @Autowired
    private JedisUtil jedisUtil;

    @Autowired(required = false)
    private ProductMapper productMapper;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @Author: yph
     * @Date: 2022/1/3 14:55
     * @return:
     * @Description: 从直连队列消费消息，进行业务处理
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_DIRECT_QUEUE_PRODUCT)
    @RabbitHandler
    public void consumeDirectMsgFromDirectQueue(Integer productId) {
        log.info("======从直连队列：{},消费消息：{} ======", RabbitMQConstant.RABBITMQ_DIRECT_EXCHANGE_PRODUCT, productId);

        // 获取jedis对象，并从redis数据库中获取所有订阅该商品到货提醒的联系方式
        Jedis jedis = jedisUtil.getJedis();
        Set<String> userPhones = jedis.hkeys(RabbitMQConstant.SUBSCRIBE_PRODUCT_PREFIX + productId);
        Product product = productMapper.selectById(productId);
        // TODO 解析消息，进行业务处理 发送短信
        userPhones.forEach(phone -> {
            // 获取每一个联系方式并将信息内容发送给对方
            jedis.set("sendMessage:" + phone, "商品[" + product.getProductName() + "]已到货，请及时下单！");
            jedis.expire("sendMessage:" + phone, 1800);
            // 键数据添加到reids中后删除相应的值
            jedis.hdel(RabbitMQConstant.SUBSCRIBE_PRODUCT_PREFIX + productId, phone);
        });
        userPhones.forEach(userPhone -> log.info("---- [{}] ----", userPhone));
    }

}
